package com.hdax.dm.common.interceptors;

import cn.hutool.crypto.asymmetric.RSA;
import com.alibaba.fastjson.JSON;
import com.hdax.dm.utils.response.CommonResponse;
import com.hdax.dm.utils.response.ResponseUtils;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
public class TokenConfig implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;
    //公钥
    private String publice_key="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxq0aEs5UDJ6laDgMMNgo0LEj4WCKIUTKqUQp0Sv0JuZYw9r+Mw9WXN5w4mkGNz7p0p6277+Jh377YPT3KgE2C3pueeZZYbd2hJbFnz8N59fcee9thpSxFLmveqnqZegP0EbzMJHXe/c2oYc7SRxWrVWnTrOVmVJgO/aunsGCtufuqwNOEkbJSnU5upNS9nETamRUjChP9SKlh1O3s7H0bO8Qs2nFY+VTjaRaHVWPuK+AQ1ne67pV6sHTCpfBXuyD3I4PVXyT8PK1vceNMUu291P7r0RjW0Bq8xGX5+PRG+gQiAeCYUfFjktB9atk1n/xg6htqdoFVmsiWWJdpPsGaQIDAQAB";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断请求路径是否包含/p/如包含就虚鉴权
        if (request.getRequestURI().contains("/p/")) {
            //获取请求头里的token
            String token = request.getHeader("token");
            //JWT 认证、解析token带有签名信息
            RSA rsa=new RSA(null,publice_key);
            RSAPublicKey rsaPublicKey= (RSAPublicKey) rsa.getPublicKey();
            JwtParserBuilder parserBuilder= Jwts.parserBuilder();
            parserBuilder.setSigningKey(rsaPublicKey);
            JwtParser jwtParser=parserBuilder.build();
            try {
                Claims claims=jwtParser.parseClaimsJws(token).getBody();
                String id=claims.getId();
                Date date=claims.getIssuedAt();
                //从redis获取token，如果无法获取那就是token过期
                String redisToken = redisTemplate.opsForValue().get("token");
                if(redisToken == null){
                    response.setContentType("application/json;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    CommonResponse commonResponse = ResponseUtils.returnFail("9999","登录超时！请重新登录");
                    out.println(JSON.toJSONString(commonResponse));
                    return false;
                }
                return true;
            }catch (Exception ex){
                //鉴权失败会进入异常
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter out = response.getWriter();
                CommonResponse commonResponse =ResponseUtils.returnFail("9999","验签失败！请重新登录");
                out.println(JSON.toJSONString(commonResponse));
                if( redisTemplate.opsForValue().get("token")!=null){
                    redisTemplate.delete("token");
                }
                return false;
            }

        }else {
            return true;
        }
    }
}
